var Promise = require('es6-promise.js')

function compareTime(h, m) {
  var date = new Date(), 
  hour = date.getHours(), 
  minute = date.getMinutes(),
  delta = (h * 60 + m - hour * 60 - minute);
  if (delta * delta < 7200) return 1;
  else return 0;
}

function formatDate(timescamp, type) {
  if (typeof timescamp !== 'number' || timescamp < 0) { return timescamp; }
  var date = new Date(timescamp),
  year = date.getFullYear(),
  month = formatNumber(date.getMonth() + 1),
  day = formatNumber(date.getDate()),
  hours = formatNumber(date.getHours()),
  minute = formatNumber(date.getMinutes()),
  second = formatNumber(date.getSeconds());
  if (type == 'chinese') return year + '年' + month + '月' + day + '日 ' + hours + '时' + minute + '分' + second + '秒';   // 中文模式
  if (type == 'datetime') return ([year, month, day]).join('-') + ' ' + ([hours, minute, second]).join(':')    // 传统模式
  if (type == 'date') return ([year, month, day]).join('/')   // 斜杠日期模式
  if (type == 'time') return ([hours, minute, second]).join(':')   // 时间模式
  return ([year, month, day]).join('-')   // 默认：日期模式
}
const formatNumber = n => { n = n.toString(); return n[1] ? n : '0' + n; }
const catchTime = i => { return [i.hour, i.minute, i.second].map(formatNumber).join(':');}

function wxPromisify(fn) {
  return function (obj = {}) {
    return new Promise((resolve, reject) => {
      obj.success = function (res) {
        resolve(res)
      }
      obj.fail = function (res) {
        reject(res)
      }
      fn(obj)
    })
  }
}

module.exports = {
  formatDate: formatDate,
  wxPromisify: wxPromisify,
  catchTime: catchTime,
  compareTime: compareTime
}